package org.edu.modules.kwgl.controller;

import java.util.*;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.edu.common.system.base.controller.BaseController;
import org.edu.common.api.vo.Result;
import org.edu.common.system.query.QueryGenerator;
import org.edu.common.system.vo.LoginUser;
import org.edu.common.util.oConvertUtils;
import org.edu.modules.kwgl.api.IVeJwJxzyFeignClientService;
import org.edu.modules.kwgl.entity.*;
import org.edu.modules.kwgl.service.IVeJwCjBukaoService;
import org.edu.modules.kwgl.service.IVeJwQkXueshengService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.edu.modules.kwgl.utils.CommonAipUtils;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.edu.common.aspect.annotation.AutoLog;

 /**
 * @Description: 清考学生
 * @Author: jeecg-boot
 * @Date:   2021-05-08
 * @Version: V1.0
 */
@Api(tags="清考学生")
@RestController
@RequestMapping("/kwgl/veJwQkXuesheng")
@Slf4j
public class VeJwQkXueshengController extends BaseController<VeJwQkXuesheng, IVeJwQkXueshengService> {
	@Autowired
	private IVeJwQkXueshengService veJwQkXueshengService;
	 @Autowired
	 private IVeJwCjBukaoService veJwCjBukaoService;

	 @Autowired
	 private IVeJwJxzyFeignClientService jwJxzyFeignClientService;

	
	/**
	 * 分页列表查询
	 *
	 * @param veJwQkXuesheng
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "清考学生-分页列表查询")
	@ApiOperation(value="清考学生-分页列表查询", notes="清考学生-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(VeJwQkXuesheng veJwQkXuesheng,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<VeJwQkXuesheng> queryWrapper = QueryGenerator.initQueryWrapper(veJwQkXuesheng, req.getParameterMap());
		Page<VeJwQkXuesheng> page = new Page<VeJwQkXuesheng>(pageNo, pageSize);
		IPage<VeJwQkXuesheng> pageList = veJwQkXueshengService.page(page, queryWrapper);

		pageList.getRecords().forEach(item->{
			if(item.getCjbkid()!=null && item.getCjbkid()!=0){
				VeJwCjBukao chengji = veJwCjBukaoService.getById(item.getCjbkid());
				if(chengji.getKccj()!=null){
					item.setCjbk(chengji.getKccj().toString());
				}else if(chengji.getIspass()!=null){
					item.setCjbk(chengji.getIspass() == 1 ?"及格":"不及格");
				}
			}
		});
		return Result.ok(pageList);
	}


	/**
	 *   添加
	 *
	 * @param veJwQkXuesheng
	 * @return
	 */
	@AutoLog(value = "清考学生-添加")
	@ApiOperation(value="清考学生-添加", notes="清考学生-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody VeJwQkXuesheng veJwQkXuesheng) {
		if(veJwQkXueshengService.getByStuidAndKcid(veJwQkXuesheng.getStuid(),veJwQkXuesheng.getKcid())!=null){
			return Result.error("该学生已经加入清考名单！");
		}
		veJwQkXueshengService.save(veJwQkXuesheng);
		return Result.ok("加入清考名单成功！");
	}

	 /**
	  *   加入清考清单
	  *
	  * @param jsonObject
	  * @return
	  */
	 @AutoLog(value = "清考学生-加入清考清单")
	 @ApiOperation(value="清考学生-加入清考清单", notes="清考学生-加入清考清单")
	 @PostMapping(value = "/addById")
	 public Result<?> addById(@RequestBody JSONObject jsonObject) {
		 String id = jsonObject.getString("id");
		 if(StringUtils.isEmpty(id)){
			 return Result.error("未选择学生记录！");
		 }
		 VeJwCjBukao item = veJwCjBukaoService.getById(id);
		 if(item==null){
			 return Result.error("记录不存在！");
		 }
		 if(veJwQkXueshengService.getByStuidAndKcid(item.getStuid(),item.getKcid())!=null){
			 return Result.error("该学生已经加入清考名单！");
		 }
		 VeJwQkXuesheng xuesheng = new VeJwQkXuesheng();
		 xuesheng.setKcid(item.getKcid());
		 xuesheng.setStuid(item.getStuid());
		 xuesheng.setSemid(item.getSemid());
		 xuesheng.setSpecid(item.getSpecid());
		 xuesheng.setBkid(item.getBkid());
		 xuesheng.setCjbkid(item.getId());
		 xuesheng.setFalid(item.getFalid());
		 xuesheng.setJxbid(item.getJxbid());
		 xuesheng.setXh(item.getXh());
		 xuesheng.setXm(item.getXm());
		 xuesheng.setXzbid(item.getXzbid());
		 xuesheng.setXzid(item.getXzid());
		 xuesheng.setUserid(item.getUserid());
		 xuesheng.setGradeid(item.getGradeid());

		 long nowTime = System.currentTimeMillis()/1000;
		 Integer nowTimeInt = new Long(nowTime).intValue();
		 xuesheng.setCreatetime(nowTimeInt);
		 veJwQkXueshengService.save(xuesheng);
		 return Result.ok("加入清考名单成功！");
	 }

	 /**
	  *   批量添加清考清单
	  *
	  * @param jsonObject
	  * @return
	  */
	 @AutoLog(value = "清考学生-批量添加清考清单")
	 @ApiOperation(value="清考学生-批量添加清考清单", notes="清考学生-批量添加清考清单")
	 @PostMapping(value = "/addByIds")
	 public Result<?> addByIds(@RequestBody JSONObject jsonObject) {
		 String ids = jsonObject.getString("ids");
		 if(StringUtils.isEmpty(ids)){
			 return Result.error("未选择学生记录！");
		 }

		 LambdaQueryWrapper<VeJwCjBukao> queryWrapper=new LambdaQueryWrapper<>();
		 queryWrapper.in(VeJwCjBukao::getId,Arrays.asList(ids.split(",")));
		 List<VeJwCjBukao> chengjiList=veJwCjBukaoService.list(queryWrapper);

		 int success = 0;
		 int error = 0;
		 for(VeJwCjBukao item:chengjiList){
			 if(veJwQkXueshengService.getByStuidAndKcid(item.getStuid(),item.getKcid())!=null){
				 error++;
				 continue;
//				 return Result.error("学员【"+item.getXm()+"】该课程的补考成绩已存在！");
			 }
			 VeJwQkXuesheng xuesheng = new VeJwQkXuesheng();
			 xuesheng.setKcid(item.getKcid());
			 xuesheng.setStuid(item.getStuid());
			 xuesheng.setSemid(item.getSemid());
			 xuesheng.setSpecid(item.getSpecid());
			 xuesheng.setBkid(item.getBkid());
			 xuesheng.setCjbkid(item.getId());
			 xuesheng.setFalid(item.getFalid());
			 xuesheng.setJxbid(item.getJxbid());
			 xuesheng.setXh(item.getXh());
			 xuesheng.setXm(item.getXm());
			 xuesheng.setXzbid(item.getXzbid());
			 xuesheng.setXzid(item.getXzid());
			 xuesheng.setUserid(item.getUserid());
			 xuesheng.setGradeid(item.getGradeid());

			 long nowTime = System.currentTimeMillis()/1000;
			 Integer nowTimeInt = new Long(nowTime).intValue();
			 xuesheng.setCreatetime(nowTimeInt);
			 veJwQkXueshengService.save(xuesheng);
			 success++;
		 }
		 if(error == 0){
			 return Result.ok("加入清考名单成功！");
		 }else {
			 return Result.ok("加入清考名单成功"+success+"条学生记录，"+error+"条学生已经加入清考名单！");
		 }
	 }
	
	/**
	 *  编辑
	 *
	 * @param veJwQkXuesheng
	 * @return
	 */
	@AutoLog(value = "清考学生-编辑")
	@ApiOperation(value="清考学生-编辑", notes="清考学生-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody VeJwQkXuesheng veJwQkXuesheng) {
		veJwQkXueshengService.updateById(veJwQkXuesheng);
		return Result.ok("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "清考学生-通过id删除")
	@ApiOperation(value="清考学生-通过id删除", notes="清考学生-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		veJwQkXueshengService.removeById(id);
		return Result.ok("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "清考学生-批量删除")
	@ApiOperation(value="清考学生-批量删除", notes="清考学生-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.veJwQkXueshengService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.ok("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "清考学生-通过id查询")
	@ApiOperation(value="清考学生-通过id查询", notes="清考学生-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		VeJwQkXuesheng veJwQkXuesheng = veJwQkXueshengService.getById(id);
		if(veJwQkXuesheng==null) {
			return Result.error("未找到对应数据");
		}
		return Result.ok(veJwQkXuesheng);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param veJwQkXuesheng
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, VeJwQkXuesheng veJwQkXuesheng) {
		QueryWrapper<VeJwQkXuesheng> queryWrapper = QueryGenerator.initQueryWrapper(veJwQkXuesheng, request.getParameterMap());
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		List<VeJwQkXuesheng> pageList = this.veJwQkXueshengService.list(queryWrapper);
		List<VeJwQkXuesheng> exportList = null;
		String selections = request.getParameter("selections");
		if (oConvertUtils.isNotEmpty(selections)) {
			List<String> selectionList = Arrays.asList(selections.split(","));
			exportList = (List)pageList.stream().filter((item) -> {
				return selectionList.contains(item.getId());
			}).collect(Collectors.toList());
		} else {
			exportList = pageList;
		}
		List<VeJwQkXueshengExcel> array=new ArrayList<>();
//		map存key减少重复查询
		Map<Integer,String> zybMap = CommonAipUtils.getZybIdNameMap();
		Map<Integer,String> njMap = CommonAipUtils.getGradeIdNameMap();
		Map<Integer,String> zyMap = new HashMap<>();

		Map<Integer,String> cjMap = new HashMap<>();
		QueryWrapper chengjiWrapper = QueryGenerator.initQueryWrapper(veJwQkXuesheng, request.getParameterMap());
		List<VeJwCjBukao> chengjis = this.veJwCjBukaoService.list(chengjiWrapper);
		for(VeJwCjBukao chengji:chengjis){
			if (chengji.getKccj() != null) {
				cjMap.put(chengji.getId(),chengji.getKccj().toString());
			} else if (chengji.getIspass() != null) {
				cjMap.put(chengji.getId(),chengji.getIspass() == 1 ? "及格" : "不及格");
			}
		}


		Map<Integer,String> kcMap = new HashMap<>();

		for(VeJwQkXuesheng item:exportList){
			VeJwQkXueshengExcel excelItem = new VeJwQkXueshengExcel();
//			设置考试名称

			excelItem.setXh(item.getXh());
			excelItem.setXm(item.getXm());

			if(cjMap.containsKey(item.getCjbkid())){
				excelItem.setCjbk(cjMap.get(item.getCjbkid()));
			}

//			专业部名称
			if(item.getFalid()!=null && zybMap.containsKey(item.getFalid())){
				excelItem.setFalidName(zybMap.get(item.getFalid()));
			}
//			年级名称
			if(item.getGradeid()!=null && njMap.containsKey(item.getGradeid())){
				excelItem.setGradeidName(njMap.get(item.getGradeid()));
			}
//			获取专业名称
			if(item.getSpecid()!=null){
				if(!zyMap.containsKey(item.getSpecid())){
					zyMap.put(item.getSpecid(),CommonAipUtils.getZyById(item.getSpecid()));
				}
				excelItem.setSpecidName(zyMap.get(item.getSpecid()));
			}

			if(item.getKcid()!=null && item.getKcid() != 0 ){
				if(!kcMap.containsKey(item.getKcid())){
					kcMap.put(item.getKcid(),jwJxzyFeignClientService.getKcNameById(item.getKcid()));
				}
				excelItem.setKcidName(kcMap.get(item.getKcid()));
			}

//			获取班级名称
//			if(item.getXzbid()!=null){
//				if(!banjiMap.containsKey(item.getXzbid())){
//					banjiMap.put(item.getXzbid(),CommonAipUtils.getBanjiById(item.getXzbid()));
//				}
//				excelItem.setXzbidName(banjiMap.get(item.getXzbid()));
//			}

			excelItem.setQkqk(item.getQkid()==null || item.getQkid() == 0 ?"未安排":"已安排");
			array.add(excelItem);
		}

		ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		mv.addObject("fileName", "清考学生");
		mv.addObject("entity", VeJwQkXueshengExcel.class);
		mv.addObject("params", new ExportParams("清考学生", "导出人:" + sysUser.getRealname(), "清考学生"));
		mv.addObject("data", array);
		return mv;
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, VeJwQkXuesheng.class);
    }

}
